<template>
  <div>
    <div>
      <el-form :inline="true" :model="user" class="demo-form-inline">
        <el-form-item label="姓名">
          <el-input v-model="user.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="user.role" placeholder="请选择角色">
            <el-option label="机构管理员" value="机构管理员"></el-option>
            <el-option label="发布人员" value="发布人员"></el-option>
            <el-option label="审核人员" value="审核人员"></el-option>
            <el-option label="学员" value="学员"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="账号状态">
          <el-select v-model="user.status" placeholder="请选择角色">
            <el-option label="正常" value="正常"></el-option>
            <el-option label="注册未审核" value="注册未审核"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="show">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="clear">清空</el-button>
        </el-form-item>

        <el-form-item style="float: left">
          <el-button type="primary" @click="add">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="exportData">导出</el-button>
        </el-form-item>

        <el-form-item>
          <el-button type="danger" @click="importData">导入</el-button>
        </el-form-item>



        <el-form-item style="float: right">

          <el-button type="danger" @click="deleteByIds">批量删除选中</el-button>
        </el-form-item>


      </el-form>

      <div>
        <el-table
            id="tableId"
            v-loading="loading"
            max-height="500"
            highlight-current-row
            ref="multipleTable"
            tooltip-effect="dark"
            border
            @selection-change="handleSelectionChange"
            :data="tableData"
            style="margin: 0 auto; width: 100%;"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="id" label="编号" header-align="center" align="center"></el-table-column>
          <el-table-column prop="name" label="姓名" header-align="center" align="center"></el-table-column>

          <el-table-column prop="password" label="密码" header-align="center" align="center"></el-table-column>

          <el-table-column prop="role" label="角色" header-align="center" align="center"></el-table-column>
          <el-table-column prop="agencyId" label="归属机构" header-align="center" align="center">
            <template slot-scope="scope">
              {{ getAgencyName(scope.row.agencyId) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="账号状态" header-align="center" align="center"></el-table-column>
          <el-table-column label="操作" width="400" header-align="center" align="center">
            <template slot-scope="scope">
              <el-button v-show="scope.row.status==='正常'"
                         size="mini"
                         type="primary"
                         plain
                         @click="updateInfo(scope.row.id)"
              >编辑
              </el-button>
              <el-button v-show="scope.row.status==='注册未审核'"
                         size="mini"
                         type="primary"
                         plain
                         @click="updateInfo(scope.row.id)"
              >审核
              </el-button>
              <el-button
                  size="mini"
                  type="danger"
                  plain
                  @click="deleteById(scope.row.id)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-dialog :visible.sync="dialogVisible" :before-close="close">
        <el-form :model="user" size="mini">
          <el-form-item label="姓名" :label-width="formLabelWidth">
            <el-input v-model="user.name" placeholder="请输入姓名" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" :label-width="formLabelWidth">
            <el-input v-model="user.password" placeholder="请输入密码" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
              label="手机号"
              :label-width="formLabelWidth"
              prop="phone"
              :rules="[
            { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
            ]">
            <el-input v-model="user.phone" placeholder="请输入手机号" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
              label="身份证号"
              :label-width="formLabelWidth"
              prop="idNumber"
              :rules="[
            { pattern: /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/, message: '身份证号格式不正确', trigger: 'blur' }
            ]">
            <el-input v-model="user.idNumber" placeholder="请输入身份证号" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="归属机构" :label-width="formLabelWidth" v-show="user.agencyId!==0">
            <el-select v-model="user.agencyId" placeholder="请选择" style="width:100%">
              <el-option
                  v-for="item in agencyList"
                  :key="item.value"
                  :label="item.name"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="角色" :label-width="formLabelWidth">
            <el-select v-model="user.role" placeholder="请选择角色" style="width:100%">
              <el-option label="机构管理员" value="机构管理员"></el-option>
              <el-option label="发布人员" value="发布人员"></el-option>
              <el-option label="审核人员" value="审核人员"></el-option>
              <el-option label="学员" value="学员"></el-option>
            </el-select>
          </el-form-item>
        </el-form>


        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false;clear()">取 消</el-button>
          <el-button v-show="user.status==='正常'" type="primary" @click="addForm()">确 定</el-button>
          <el-button v-show="user.status==='注册未审核'" type="primary" @click="addForm()">确 定</el-button>
        </div>
      </el-dialog>


    </div>

    <br>
    <!--分页工具条-->
    <footer>
      <el-pagination
          style="position:absolute;bottom: 20px;margin-left: 40vh"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :background="background"
          :current-page="currentPage"
          :page-sizes="[5, 10]"
          :page-size="5"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount">
      </el-pagination>
    </footer>
  </div>


</template>
<script>


import {addUser, addUsers, changeUser, deleteUser, getAllUsers} from "@/api/user";
import {getAgencyList} from "@/api/agency";
import FileSaver from "file-saver";
import * as XLSX from "xlsx";

export default {
  data() {
    return {
      background: true,
      // 每页显示的条数
      pageSize: 5,
      // 总记录数
      totalCount: 100,
      // 当前页码
      currentPage: 1,
      // 添加数据对话框是否展示的标记
      dialogVisible: false,
      // 表格数据
      tableData: [],
      addOrUpdate: true,//true为add
      user: {"password": "1234567"},
      form: {},
      posts: [],
      multipleSelection: [],
      selectedIds: [],
      agencyList: [],
      formLabelWidth: "80px",
      theMajorOfMy: "",
      loading: false,
    }
  },
  methods: {
    validateAge(rule, value, callback) {
      if (value === undefined || value === null || value === '') {
        return callback(new Error('请输入年龄'));
      }
      if (value < 0 || value > 100) {
        callback(new Error('年龄必须在0到100之间'));
      } else {
        callback();
      }
    },
    show() {

      getAllUsers(this.user, this.currentPage, this.pageSize).then((res) => {
        //console.log(res)
        if (res.data.code === 1) {
          this.totalCount = res.data.data.total;
          this.tableData = res.data.data.rows;
          if (this.tableData.length === 0 && this.currentPage > 1) {
            this.currentPage -= 1;
            this.show()
          }
          //console.log(this.tableData)
        }
      }).catch((e) => {
      })
    },
    clear() {
      this.user = {};
      this.show();
    },
    add() {
      this.user = {};
      this.user.password = "1234567";
      this.addOrUpdate = true;
      this.dialogVisible = true;
    },
    addForm() {

      if (this.addOrUpdate) {
        addUser(this.user).then(res => {
          if (res.data.code === 1) {
            this.$message.success("保存成功")
            this.dialogVisible = false;
            this.show();
          } else {
            this.$message.error(res.data.msg)
          }
        }).catch(e => {
        });
      } else {
        changeUser(this.user).then(res => {
          console.log(res)
          if (res.data.code === 1) {
            this.$message.success("更新成功")
            this.dialogVisible = false;
            this.user.status = "正常";
            this.show();
          }
        }).catch(e => {
        });
      }

    },

    close() {
      this.dialogVisible = false;
      this.user = {}
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    updateInfo(id) {
      this.addOrUpdate = false;
      this.user = this.tableData.filter(data => data.id == id)[0];
      this.dialogVisible = true;
    },
    deleteById(id) {
      this.$refs.multipleTable.clearSelection();
      this.$refs.multipleTable.toggleRowSelection(this.tableData.filter(data => data.id === id)[0]);
      this.deleteByIds()
    },
    deleteByIds() {

      // 弹出确认提示框
      this.$confirm("此操作将删除数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        //用户点击确认按钮
        //1. 创建id数组, 从 this.multipleSelection 获取即可
        for (let i = 0; i < this.multipleSelection.length; i++) {
          this.selectedIds[i] = this.multipleSelection[i].id;
        }
        //console.log(this.selectedIds);
        //2. 发送AJAX请求
        deleteUser(this.selectedIds).then((resp) => {
          if (resp.data.code === 1) {
            //删除成功
            this.$message.success("恭喜你，删除成功");
            this.show();
          } else {
            this.$message.error(resp.data.msg);
          }
        }).catch(() => {
        });

      }).catch(() => {
        //用户点击取消按钮
        this.$message.info("已取消删除");
      });

    },
    getAllAgencyList() {
      getAgencyList().then((res) => {
        if (res.data.code === 1) {
          this.agencyList = res.data.data;
        }
      }).catch((e) => {
      })
    },
    getAgencyName(id) {
      if (id === 0) {
        return "超级管理员";
      }
      let agency = this.agencyList.find(data => data.id === id);
      return agency ? agency.name : "";
    },
    //分页
    handleSizeChange(val) {
      // 重新设置每页显示的条数
      this.pageSize = val;
      this.show();
    },
    handleCurrentChange(val) {
      // 重新设置当前页码
      this.currentPage = val;
      this.show();
    },


    //导出
    async exportData() {
      this.loading = true;
      this.currentPage = 1;
      this.pageSize = this.totalCount;

      try {
        await getAllUsers(this.user, this.currentPage, this.pageSize).then((res) => {
          if (res.data.code === 1) {
            //将learningSituationList拆开放入属性中
            const data = this.tableData;

            // 创建工作簿对象
            const wb = XLSX.utils.book_new();

            // 将数据添加到工作簿中，假设 data 是一个二维数组或对象数组
            // 如果 data 是对象数组，使用 XLSX.utils.json_to_sheet(data)
            // 如果 data 是二维数组，使用 XLSX.utils.aoa_to_sheet(data)
            const ws = XLSX.utils.json_to_sheet(data);

            // 将工作表添加到工作簿中
            XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
            // 写入工作簿，生成 XLSX 文件
            const wbout = XLSX.write(wb, {bookType: 'xlsx', type: 'array'});
            // 使用 FileSaver 保存文件
            try {
              FileSaver.saveAs(
                  new Blob([wbout], {type: "application/octet-stream"}),
                  this.getAgencyName(this.tableData[0].agencyId) + "_机构账号信息.xlsx"
              );
            } catch (e) {
              console.error(e);
            }


          }
        }).catch((e) => {
        })
      } finally {
        this.currentPage = 1;
        this.pageSize = 5;
        this.show();
        this.loading = false;
      }
    },

    async importData() {
      // 创建一个文件输入元素
      const inputElement = document.createElement('input');
      inputElement.type = 'file';
      inputElement.accept = '.xlsx, .xls'; // 接受的文件类型
      // 当文件被选中时触发读取操作
      inputElement.addEventListener('change', async (event) => {
        const file = event.target.files[0];
        if (!file) {
          return;
        }
        try {
          // 读取文件
          const data = await this.readFile(file);
          // 使用 XLSX 解析文件
          const workbook = XLSX.read(data, {type: 'array'});
          // 获取第一个工作表
          const worksheet = workbook.Sheets[workbook.SheetNames[0]];
          // 将工作表转换为 JSON
          const jsonData = XLSX.utils.sheet_to_json(worksheet, {header: 1});
          // 处理导入的数据
          this.processImportedData(jsonData);
        } catch (e) {
          console.error(e);
        }
      });
      // 触发文件选择
      inputElement.click();
    },

    // 读取文件为 ArrayBuffer
    readFile(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (e) => {
          resolve(e.target.result);
        };
        reader.onerror = reject;
        reader.readAsArrayBuffer(file);
      });
    },

    // 处理导入的数据
    processImportedData(data) {
      // 根据你的需求处理导入的数据
      console.log(data);
      // 例如，你可以将数据添加到你的应用状态中，或者更新数据库等
      const headers = data[0]; // 第一行是列标题
      const dataObjects = data.slice(1).map(row => { // 从第二行开始是数据
        const obj = {};
        headers.forEach((header, index) => {
          obj[header] = row[index] === undefined ? null : row[index];
        });
        return obj;
      });
      addUsers(dataObjects).then((res) => {
         if(res.data.code===1){
           this.$message.success("添加成功");
         }
      }).catch((e) => {})

    },

  },
  mounted() {
    this.show();
    this.getAllAgencyList();
  },
};
</script>


<style>
* {
  margin: 0;
  padding: 0;
}

.el-header {
  background-color: rgb(238, 241, 246);
  color: #333;
  line-height: 60px;
}

.el-aside {
  color: white;
}

</style>
<script setup>
</script>
